package top.chenyaohua.driver;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {

    private static ConnectionPool connectionPool;

    /**
     * 链接池
     */
    private  List<Connection> connectionList;
    /**
     * 最小链接数
     */
    private int min;
    /**
     * 最大连接数
     */
    private int max;
    /**
     * 当前连接数
     */
    private int current;

    private ConnectionPool(int min,int max) {
        List<Connection> ls = new ArrayList<>();
        for (int i = 0; i < min; i++) {
            Connection install = ConnectionFactory.getInstall();
            ls.add(install);
        }
        this.connectionList = ls;
        this.current = min;
        this.max = max;
        this.min = min;
    }

    public static ConnectionPool newInstall() {
        if(connectionPool == null){
            synchronized (ConnectionPool.class){
                if(connectionPool == null){
                    connectionPool = new ConnectionPool(10,100);
                }
            }
        }
        return connectionPool;
    }

    /**
     * 获取一个链接
     * @return
     */
    public  synchronized Connection getConnection(){
        if (this.connectionList.isEmpty()) {
            if( this.current < this.max ){
                Connection install = ConnectionFactory.getInstall();
                this.connectionList.add(install);
                this.current++;
            }else{
                throw new RuntimeException("链接池链接超过最大连接数");
            }
        }
        Connection connection = this.connectionList.get(0);
        this.connectionList.remove(connection);
        return connection;
    }


    public  synchronized  void setConnection(Connection sql){
        this.connectionList.add(sql);
    }
}
